<template>
  <div class="app-container">
    <!--选择仓库-->
    <SelectWarehouse ref="openSelectWarehouse"></SelectWarehouse>
    <WarehouseInDetailHistory ref="openWarehouseInDetailHistory" @refresh="refresh"></WarehouseInDetailHistory>
    <WarehouseInDetailEdit ref="openWarehouseInDetailEdit" @refresh="refresh"></WarehouseInDetailEdit>
    <!-- 货物入仓详情 -->
    <div class="detail-title-box">
      <span>详情信息</span>
    </div>
    <el-form ref="form" :model="detailsQuery" size="small" :inline="true" :label-position="labelPosition" label-width="120">
      <el-form-item label="编号:" prop="pzbh">
        <el-input
          v-model="detailsQuery.pzbh"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item label="外部单号:" prop="wbdh">
        <el-input
          v-model="detailsQuery.wbdh"
          placeholder="请输入外部单号"
          clearable
          :disabled="getAuditState == 0 || getAuditState == 2"
        />
      </el-form-item>
      <el-form-item label="车牌" prop="dzzy6">
        <el-input
          v-model="detailsQuery.dzzy6"
          placeholder="请输入车牌"
          clearable
          :disabled="getAuditState == 0 || getAuditState == 2"
        />
      </el-form-item>
      <el-form-item label="司机" prop="dzzy7">
        <el-input
          v-model="detailsQuery.dzzy7"
          placeholder="请输入司机姓名"
          clearable
          :disabled="getAuditState == 0 || getAuditState == 2"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="dzzy8">
        <el-input
          v-model="detailsQuery.dzzy8"
          placeholder="请输入电话"
          clearable
          :disabled="getAuditState == 0 || getAuditState == 2"
        />
      </el-form-item>
      <el-form-item label="身份证" prop="dzzy10">
        <el-input
          v-model="detailsQuery.dzzy10"
          placeholder="请输入身份证"
          clearable
          :disabled="getAuditState == 0 || getAuditState == 2"
        />
      </el-form-item>
      <el-form-item label="备注" prop="dzbz">
        <el-input
          v-model="detailsQuery.dzbz"
          placeholder="请输入备注"
          clearable
          :disabled="getAuditState == 0 || getAuditState == 2"
        />
      </el-form-item>
      <el-form-item>
        <el-checkbox label="不计算装卸费" v-model="detailsQuery.iszxf" true-label="0" :disabled="getAuditState == 0 || getAuditState == 2"></el-checkbox>
        <el-checkbox label="不计算作业量" v-model="detailsQuery.iszyl" true-label="0" :disabled="getAuditState == 0 || getAuditState == 2"></el-checkbox>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleAddGoods" v-if="getAuditState == 1 && getdetailsData" v-hasPermi="['zhcloud:hwrc:add']">新增货物</el-button>
      </el-col>
        <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleHistoryRecord" v-hasPermi="['zhcloud:hwrc:list']">历史记录</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="warehouseInDetails"
      show-summary
      :summary-method="getSummaries"
    >
      <af-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="left">
      <template slot-scope="scope">
        <el-button
          :disabled="getAuditState == 0 || getAuditState == 2"
          size="mini"
          type="text"
          @click="handleEdit(scope.row)"
          v-hasPermi="['zhcloud:hwrc:modify']"
        >修改</el-button>
        <el-button
        :disabled="getAuditState == 0 || getAuditState == 2"
          size="mini"
          type="text"
          @click="handleDelete(scope.row)"
          v-hasPermi="['zhcloud:hwrc:del']"
        >删除</el-button>
      </template>
      </af-table-column>
      <af-table-column prop="ssrqid" label="入仓日期"  fixed="left"></af-table-column>
      <af-table-column prop="spzs" label="物品规格"  ></af-table-column>
      <af-table-column prop="spbh" label="批号" ></af-table-column>
      <af-table-column prop="spgh" label="柜号" ></af-table-column>
      <af-table-column prop="spjs" label="件数" ></af-table-column>
      <af-table-column prop="spjsl" label="单重(Kg)" ></af-table-column>
      <af-table-column prop="spsl" label="重量(吨)" ></af-table-column>
      <af-table-column prop="spcd" label="品牌" ></af-table-column>
      <af-table-column prop="spckmc" label="仓库" ></af-table-column>
      <af-table-column prop="ckcw" label="仓位" width="80"></af-table-column>
      <af-table-column prop="spkhmc" label="客户" ></af-table-column>
      <af-table-column prop="sptm" label="客户条码" ></af-table-column>
      <af-table-column prop="sptmc" label="仓库条码" ></af-table-column>
      <af-table-column prop="spbz" label="备注"></af-table-column>
    </el-table>
    <el-row type="flex" justify="center" :gutter="5" class="mt20">
      <el-col :span="1.5">
        <el-button type="primary" @click="warehouseInSubmit" v-if="getAuditState == 1 && getdetailsData" v-hasPermi="['zhcloud:hwrc:audit']">审 核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="warehouseInReject" v-if="getAuditState == 2 && getdetailsData" v-hasPermi="['zhcloud:hwrc:reject']">驳 回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button @click="editDetail" v-if="getAuditState == 1 && getdetailsData" v-hasPermi="['zhcloud:hwrc:modify']">保存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button @click="goBack">返回</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import SelectWarehouse from "./selectWarehouse.vue"
import WarehouseInDetailHistory from './warehouseInDetailHistory.vue'
import WarehouseInDetailEdit from './warehouseInDetailEdit.vue'
import { warehouseInModifyInfo, getWarehouseInDetails, warehouseInDelete, warehouseInAudit, warehouseInReject } from "@/api/storage/commonGoods/warehouseIn";
import { NUMBER_DIDGIT, WEIGHT_DIGIT } from '@/utils/constant'
import { calculateDays, formatDate } from '@/utils'

export default {
  name: "WarehouseInDetail",
  components: { SelectWarehouse, WarehouseInDetailHistory, WarehouseInDetailEdit },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //对齐方式
      labelPosition:"right",
      //表格加载
      loading: true,
      // 详情信息
      detailsQuery: {
       	dzbz: "",
        dzid: "",
        dzzy10: "",
        dzzy6: "",
        dzzy7: "",
        dzzy8: "",
        iszxf: "",
        iszyl: "",
        wbdh: "",
        pzbh:"",
        khmc:""
      },
      //获取详情参数
      queryParams:{
        dzid:"",
        shztn:"0"
      },
      //删除详情
      delQureyParams: {
        dzid: 0,
        prrq: "",
        spckid: "",
        spcwid: "",
        spdzld: 0
      },
      //审核入参
      auditQureyParams:[{
        dzid: 0,
        dzzy10: "",
        dzzy6: "",
        dzzy7: "",
        dzzy8: "",
        khmc: "",
        khmcid: "",
        pzbh: ""
      }],
      //是否审核
      auditState:0,
      //驳回入参
      rejectQureyParams:{
        dzid:"",
      },
      //行数据
      warehouseInDetails:[],
      //页数
      pageSize: 999,
      //页码
      pageNum:1,
      // 总条数
      total: 0,
    };
  },
  beforeRouteEnter(to, from, next) {
    const query = to.query
    next(vm => {   
      if(Object.keys(query).length > 0) {
        vm.reset(vm)
        vm.queryParams.dzid =  query.dzid
        vm.delQureyParams.dzid = query.dzid
        vm.delQureyParams.prrq = query.prrq
        vm.rejectQureyParams.dzid = query.dzid
        vm.getList()
      }
    })
  },
  computed: {
    getAuditState() {
      //无状态时:0,未审核:1，已审核：2
      return this.auditState === '未审核'?1:this.auditState === '已审核'?2:0
    },
    getdetailsData() {
      return this.warehouseInDetails.length > 0?true:false
    }
  },
  methods: {
    /**获取详情数据 */
    getList() {
      this.loading = true
      getWarehouseInDetails(this.queryParams).then(response => {
        const data = response.data
        if(data && data.info) {
          this.detailsQuery = data.info
          this.auditState = data.info.shzt
        }
        if(data && data.list) this.warehouseInDetails = data.list
        this.loading = false
      });
    },
    /**删除详情 */
    deleteWarehouseInDetail() {
      this.$modal.loading("数据正在删除中，请稍等...")
      warehouseInDelete(this.delQureyParams).then(response => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('删除成功！')
        this.getList()
      }).catch(()=> {
        this.$modal.closeLoading()
      })
    },

    /**审核 */
    auditWarehouseIn() {
      this.$modal.confirm("是否确认次操作？").then(() => {
        this.$modal.loading("数据正在审核中，请稍等...")
        warehouseInAudit(this.auditQureyParams).then(response => {
          warehouseInModifyInfo(this.detailsQuery).then(response => {
            this.$modal.closeLoading()
            this.$modal.msgSuccess('审核通过！')
            this.goWarehouseIn()
          }).catch(()=> {
            this.$modal.closeLoading()
          })
        }).catch(()=> {
          this.$modal.closeLoading()
        })
      }).catch(() => {})
    },

    /**驳回 */
    rejectWarehouseIn() {
      this.$modal.confirm("是否确认次操作？").then(() => {
        this.$modal.loading("数据正在驳回中，请稍等...")
        warehouseInReject(this.rejectQureyParams).then(response => {
          this.$modal.closeLoading()
          this.$modal.msgSuccess('审核驳回！')
          this.goWarehouseIn()
        }).catch(()=> {
          this.$modal.closeLoading()
        })
      }).catch(() => {})
    },
    /**保存 */
    editDetail(){
      this.$modal.loading("数据正在保存中，请稍等...")
      warehouseInModifyInfo(this.detailsQuery).then(response => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('保存成功！')
        this.goWarehouseIn()
      }).catch(()=> {
        this.$modal.closeLoading()
      })
      
    },
    /**新增货物 */
    handleAddGoods() {
      if(this.warehouseInDetails.length == 0) return
      const row = this.warehouseInDetails[0]
      const queryData = {
        ...this.detailsQuery,
        spckid:row.spckid,
        spckmc:row.spckmc,
      }
      this.$router.push({path:"/storage/commonGoods/warehouseIn/sceneWarehouseInAdd", query:queryData})
    },

    /**历史记录 */
    handleHistoryRecord() {
      this.$refs.openWarehouseInDetailHistory.open(this.detailsQuery)
    },

    /**编辑行 */
    handleEdit(row) {
      if(!row.itbz) row.itbz = ""
      const data = JSON.parse(JSON.stringify(row))
      this.$refs.openWarehouseInDetailEdit.open(data, this.queryParams.dzid)
    },
    /**删除行 */
    handleDelete(row) {
      this.$modal.confirm("是否删除记录？").then(() => {
        this.delQureyParams.spckid = row.spckid
        this.delQureyParams.spcwid = row.spcwid
        this.delQureyParams.spdzld = row.spdzld
        this.delQureyParams.spbhid = row.spbhid
        this.deleteWarehouseInDetail()
      }).catch(() => {})
    },
     //合计
    getSummaries({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if(index === 0) {
          sums[index] = "合计"
			    return
        }
        if ((column.property === "spjs" || column.property === "spsl")) {
          const values = data.map((item) => {
            return parseFloat(this.delcommafy(item[column.property]))
          });
          sums[index] = values.reduce((prev, curr) => {
            if(!prev) prev = 0
            if(!curr) curr = 0
            if(column.property === "spsl") {
              return parseFloat((prev + curr).toFixed(WEIGHT_DIGIT))
            }
            if(column.property === "spjs") {
              return parseFloat((prev + curr).toFixed(NUMBER_DIDGIT))
            }
          }, 0);
        }
      })
      return sums
    },
    /**提交审核 */
    warehouseInSubmit() {
      const nowDate = formatDate(Date.now()).split(" ")[0]
      const details = this.warehouseInDetails
      if(this.auditState  == "已审核") return this.$modal.msgWarning("已审核的单不允许再次审核！")
      //如果当前时间（审核日期）小于出仓日期，则系统提示：出仓日期大于当前日期，审核失败！
      if(details && details.length > 0) {
        const sortDetails = details.sort((a,b) => a.ssrqid>b.ssrqid?-1:1)
        if(calculateDays(sortDetails[0].ssrqid, nowDate) < 0) return this.$modal.msgWarning("入仓日期大于当前日期，审核失败！")
      }
      this.auditQureyParams = [{
        dzid: this.detailsQuery.dzid,
        dzzy10: this.detailsQuery.dzzy10,
        dzzy6: this.detailsQuery.dzzy6,
        dzzy7: this.detailsQuery.dzzy7,
        dzzy8: this.detailsQuery.dzzy8,
        khmc: this.detailsQuery.khmc,
        khmcid: this.detailsQuery.khmcid,
        pzbh: this.detailsQuery.pzbh
      }]
      this.auditWarehouseIn()
    },
    /** 驳回*/
    warehouseInReject() {
      this.rejectWarehouseIn()
    },
     /** 刷新数据*/
    refresh() {
      this.getList()
    },
     //跳回货物入仓页
    goWarehouseIn() {
      this.$tab.closePage(this.$route)
      this.$router.push({name:"WarehouseIn", params:{refresh:true}})
    },
    reset(vm) {
      Object.assign(vm.$data, vm.$options.data())
    },
     /**返回不刷新 */
    goBack() {
      this.$router.push({name:"WarehouseIn"})
    }
  }
};
</script>
